//导入插件;
import jwt from 'jsonwebtoken';

//登录;
let LoginIn=async ctx=>{
    const {username,password}=ctx.request.body;
    let res=await ctx.db.querys(`select * from user where username ='${username}'`);
    if(!res.length) return ctx.body={code:0,msg:'用户不存在'};
    if(res[0].password!==password) return ctx.body={code:0,msg:'密码错误'};
    if(res[0].state==='freeze') return ctx.body={code:0,msg:'该账户已经进入小黑屋了，请耐心等待...'};
    let lastlogin=res[0].lastlogin=new Date().getTime();
    await ctx.db.querys(`update user set lastlogin='${lastlogin}' where username='${username}'`)
    let token=jwt.sign({...res[0],lastlogin:new Date().getTime()},'userinfo')
    ctx.cookies.set('token',token);
    ctx.body={code:1,msg:'登录成功',data:{userid:res[0].userid,username:res[0].username}};
}

//修改密码;
let ChangePassword=async (ctx)=>{
    const{userid,oldpassword,newpassword}=ctx.request.body;
    console.log(userid,oldpassword,newpassword)
    const userdata=await ctx.db.querys(`select * from user where userid='${userid}'`);
    let arr=userdata.filter(item=>item.password===oldpassword);
    if(!arr.length) return ctx.body={code:0,msg:'修改失败，信息错误'};
    ctx.db.querys(`update user set password='${newpassword}' where userid='${userid}'`);
    await ctx.cookies.set('token','',{maxAge:0,signed:false});
    ctx.body={code:1,msg:'修改成功'};
}

//退出;
let LoginOut=async (ctx)=>{
    //设置cookies的过期时间为0，从而立即清除cookies;
    ctx.info="";
    await ctx.cookies.set('token','',{maxAge:0,signed:false})
    ctx.body={code:1,msg:'退出成功'};
}

export default {
    LoginIn,LoginOut,ChangePassword
}